/**
 * This file is part of the NatCrackerToolbox.
 * 
 * Copyright (C) 2009 - 2011 Peerialism Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 **/
package com.peerialism.natcracker.discovery;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class DiscoveryInterface {

	public static List<DiscoveryInfoBehave> discover(InetAddress[] myAddresses,
			String[] stunServers) {

		List<DiscoveryInfoBehave> infoSet = new LinkedList<DiscoveryInfoBehave>();
		int count = 0;

		for (int i = 0; i < myAddresses.length; i++) {
			InetAddress inetAddress = myAddresses[i];
			List<String> asList = Arrays.asList(stunServers);
			Collections.shuffle(asList);
			DatagramSocket socket;
			try {
				socket = new DatagramSocket();

				infoSet.add(new DiscoveryTest(inetAddress, asList.get(0))
						.test(socket));
				count++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		Collections.sort(infoSet, new DiscoveryInfoComparator());
		return infoSet;

	}
}

class DiscoveryInfoComparator implements Comparator<DiscoveryInfoBehave> {

	@Override
	public int compare(DiscoveryInfoBehave arg0, DiscoveryInfoBehave arg1) {

		DiscoveryInfoBehave info0 = (arg0);
		DiscoveryInfoBehave info1 = (arg1);

		return priotiryLevel(info0) - priotiryLevel(info1);

	}

	private int priotiryLevel(DiscoveryInfoBehave info) {
		int ret = 0;

		switch (info.getNatDevice().getGatewayType()) {
		case OpenInternet:
			ret = 0;
			break;

		case NAT:
			ret = 4;
			break;

		case UdpBlockingFirewall:
			ret = 5;
			break;

		default:
			break;
		}

		return ret;
	}

}